<template>
  <view>
    <view class="address-info" @click="selectAddress">
      <image class="address-map" :src="require('../../static/address/map.png')" mode="scaleToFill" />
      <view class="address-info-text">{{ addressInfo }}</view>
      <image class="address-up" :src="require('../../static/address/up.png')" mode="scaleToFill" />
    </view>
    <scroll-view scroll-y :style="{ maxHeight: `calc(100vh - ${height + 60}px)` }" @scrolltolower="scrollListower">
      <view class="address-item" v-for="(item, index) in validList" :key="index">
        <view class="address-item-top">
          <view class="address-item-outletsName">{{ item.outletsName }}</view>
          <view class="address-item-outletsAddress">
            <view class="address-item-outletsAddress-detail" v-if="isLogin">
              {{ item.detail }}
              <image style="width: 18rpx; height: 14rpx;" :src="require('../../static/address/up-ac.png')"
                mode="scaleToFill" />
            </view>
            <view v-if="!isLogin"></view>
            <view class="address-item-outletsAddress-phone" @click="openMap(item)">
              <image style="width: 21rpx; height: 17rpx; margin-right: 10rpx;"
                :src="require('../../static/address/dh.png')" mode="scaleToFill" />
              <text>{{ (item.distance / 1000).toFixed(2) }}KM</text>
            </view>
          </view>
          <view class="address-item-outletsPhone" v-if="isLogin" @click="callPhone(item)">
            <image style="width: 18rpx; height: 24rpx; margin-right: 10rpx;"
              :src="require('../../static/address/phone.png')" mode="scaleToFill" />
            <text class="phone-text">{{ item.telephone.split(',')[0] }}</text>
          </view>
          <view class="address-item-outletsPhone" v-if="!isLogin">
            <text class="phone-text" @click.stop="loginUser()">登录后可见更多信息</text>
          </view>
          <view class="address-item-tags">
            <view class="tag" v-for="(tag, index) in item.procScopeDesc && item.procScopeDesc.split(',')" :key="index">
              {{ tag }}</view>
          </view>
        </view>

        <view class="address-item-line" v-if="isLogin"></view>
        <view class="address-item-time" v-if="isLogin">{{ item.procTime }}</view>
      </view>
    </scroll-view>
    <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
      <view class="uni-popup">
        <view class="line" hover-class="none" hover-stop-propagation="false"></view>

        <view class="popup-top" v-for="item in phoneList" :key="item" @click="selectPhone(item)">
          <view class="item">{{ item }}</view>

        </view>
      </view>
    </uni-popup>
    <authorize @onLoadFun="onLoadFun" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
  </view>
</template>

<script>
import { getNearbyListApi } from '@/api/tools.js'
import Routine from "@/libs/routine.js";
import { mapGetters } from "vuex";
import Authorize from "@/components/Authorize.vue";
export default {
  components: {
    Authorize,
  },
  props: {
    height: {
      type: Number,
      default: 0
    },
    selectList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    validList() {
      const source = this.selectList.length ? this.selectList : this.list;
      return source.filter(item => !!item); // 过滤无效项
    },
    ...mapGetters(["isLogin"])

  },
  data() {
    return {
      lon: {},
      addressInfo: '请选择地理位置',
      isAuthLocation: false, //是否授权位置
      where: {
        pageNum: 1,
        pageSize: 10,
        outletsName: '',
      },
      list: [],
      total: 0,
      isShowAuth: false,
      debounceTimer: null,
      phoneList: []
    }
  },
  methods: {
    selectPhone(phone) {
      uni.makePhoneCall({
        phoneNumber: phone, // 电话号码
        success: function () {
          console.log('拨号成功');
        },
        fail: function () {
          console.log('拨号失败');
        }
      });
      let params = {
        Um_Key_ButtonName: '征信网点查询' + '-' + '拨打电话',
        Um_Key_SourcePage: '征信网点查询',
      }
      this.$umaTrack.pageClickTrack(params)
    },
    callPhone(v) {
      if (!v.telephone) return this.$util.Tips('暂无电话号码')
      if (v.telephone.split(',').length == 1) return this.selectPhone(v.telephone)
      this.phoneList = v.telephone.split(',')
      this.$refs.popup.open()
    },
    authColse() {
      this.isShowAuth = false;
    },
    onLoadFun() {
      this.isShowAuth = false;
      this.where.pageNum = 1
      this.list = []
      this.getAddressList()
    },
    loginUser() {
      this.isShowAuth = true;
    },
    searchListByOutletsName(val) {
      this.list = [];
      this.where.pageNum = 1;
      this.where.outletsName = val;
      this.getAddressList(val)

    },

    linkPage() {
      if (!this.isAuthLocation) return this.getLocation()
      if (!this.isLogin) return this.loginUser()
      uni.navigateTo({
        url: '/pagesTools/selectAddress/index?type=0'
      })
    },


    selectAddress() {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
        this.debounceTimer = null;
      }
      // 设置新的计时器（500毫秒防抖）
      this.debounceTimer = setTimeout(() => {
        this.linkPage();
        this.debounceTimer = null;
      }, 500);


      let params = {
        Um_Key_ButtonName: '征信网点查询' + '-' + '选择地理位置',
        Um_Key_SourcePage: '征信网点查询',
      }
      this.$umaTrack.pageClickTrack(params)
    },
    openMap(v) {
      if (!this.isLogin) return this.loginUser()
      uni.openLocation({
        latitude: Number(v.lat),
        longitude: Number(v.lon),
        success: function () {
          console.log('success');
        },
        fail: function (err) {
          console.log(err, 'fail');
        },
      });
      let params = {
        Um_Key_ButtonName: '征信网点查询' + '-' + '打开导航',
        Um_Key_SourcePage: '征信网点查询',
      }
      this.$umaTrack.pageClickTrack(params)
    },
    scrollListower() {
      if (this.where.pageNum * this.where.pageSize < this.total) {
        this.where.pageNum++
        this.getAddressList()
      } else {
        this.$util.Tips('没有更多数据了')
      }
    },
    getLocation(keyword = '') {
      let that = this;

      that.where.outletsName = keyword;
      Routine.gettLocation().then(async res => {
        that.isAuthLocation = true;
        that.lon.lon = res.longitude;
        that.lon.lat = res.latitude;
        this.$emit('getLon', res)
        await this.getAddressInfo(res.longitude, res.latitude)
        await this.getAddressList()
      })
    },

    getAddressInfo(lon, lat) {
      let that = this;
      uni.request({
        url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
        method: 'GET',
        data: {
          key: '329b1e97a844a0cf2be6e3046a5632cc',
          location: `${lon}, ${lat}`
        },
        success: async (data) => {
          that.addressInfo = data.data.regeocode.formatted_address;
        },
        fail(err) {
          console.log(err);
        }
      });
    },

    getAddressList() {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      let params = {
        ...this.lon,
        ...this.where
      }
      getNearbyListApi(params).then(res => {
        this.list = [...this.list, ...res.data.list]
        this.total = res.data.total
      }).finally(() => {
        uni.hideLoading()
      })
    },
    //自定义事件更新地址信息
    updateAddress(data) {
      if (data) {
        this.addressInfo = `${data.msg.district ? data.msg.district : ''}` + data?.msg?.name
        const dataArr = data.msg.location.split(',')
        this.lon = { lon: dataArr[0], lat: dataArr[1] }
        this.list = []
        this.where.pageNum = 1
        this.getAddressList()
      }
    },
    //自定义事件更新定位信息
    updateLocation(data) {
      if (data == 'ok') {
        this.list = []
        this.getLocation()
      } else {
        this.isAuthLocation = false
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.address-info {
  display: flex;
  align-items: center;
  height: 100rpx;
  background: #FFFFFF;
  justify-content: space-between;
  box-shadow: 0rpx 2rpx 20rpx 0rpx rgba(255, 255, 255, 0.5);
  padding: 0 30rpx;
  margin-bottom: 30rpx;

  .address-info-text {
    width: 646rpx;
    height: 40rpx;
    font-weight: 600;
    font-size: 28rpx;
    color: #333333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .address-map {
    width: 23rpx;
    height: 33rpx;
  }

  .address-up {
    width: 18rpx;
    height: 14rpx;
  }
}

.address-item {
  width: 688rpx;
  background: #FFFFFF;
  border-radius: 30rpx;
  margin: 0 auto 30rpx;

  // padding: 30rpx;
  .address-item-top {
    padding: 30rpx;
  }

  .address-item-outletsName {
    font-weight: 500;
    font-size: 32rpx;
    color: #333333;
  }

  .address-item-outletsAddress {

    display: flex;
    justify-content: space-between;
    margin-top: 10rpx;

    .address-item-outletsAddress-detail {
      width: 75%;
      font-weight: 400;
      font-size: 22rpx;
      color: #999999;
    }

    .address-item-outletsAddress-phone {
      width: 148rpx;
      height: 46rpx;
      line-height: 46rpx;
      background: #ECF3FE;
      border-radius: 23rpx;
      text-align: center;
      font-weight: 600;
      font-size: 22rpx;
      color: #2872FD;
    }

    // font-weight: 400;
    // font-size: 22rpx;
    // color: #999999;
  }

  .address-item-outletsPhone {
    display: inline-block;

    .phone-text {
      font-weight: 600;
      font-size: 34rpx;
      color: #276FF7;
    }
  }

  .address-item-tags {
    display: flex;
    align-items: center;
    margin-top: 10rpx;

    .tag {
      width: 95rpx;
      height: 30rpx;
      line-height: 30rpx;
      border-radius: 4rpx;
      border: 2rpx solid #DADADA;
      font-weight: 400;
      font-size: 22rpx;
      text-align: center;
      color: #DADADA;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }


  .address-item-line {
    width: 687rpx;
    height: 1rpx;
    background-color: #EDEDED;
  }

  .address-item-time {
    padding: 30rpx;
    font-weight: 400;
    font-size: 24rpx;
    color: #999999;
  }
}


.uni-popup {
    width: 750rpx;
    height: 634rpx;
    background: #ffffff;
    border-radius: 24rpx 24rpx 0rpx 0rpx;
    padding: 40rpx 30rpx 30rpx 30rpx;
    background-color: #fff;

    .line {
        width: 60rpx;
        height: 6rpx;
        background: #e6e6e6;
        border-radius: 5rpx;
        margin: auto;
    }

    .popup-top {
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-direction: row;
        align-items: center;
        border-bottom: 1px solid #eee;
        padding-top: 20rpx;
        padding-bottom: 20rpx;
    }

    image {
        width: 95rpx;
        height: 50rpx;
    }
}
.item {
    font-size: 30rpx;
    margin: 10rpx auto;
    font-weight: bold;
    // margin-bottom: 30rpx;
    // margin-top: 30rpx;
}
</style>